import Food from './Food';
import ScorePanel from "./ScorePanel";
import Snake from "./Snake"
import snake from "./Snake";
class GameControl{
    snake:Snake;
    scorepanel:ScorePanel;
    food:Food;
    direction:string='';
    isAlive:boolean=true;
    constructor() {
        this.snake=new Snake();
        this.scorepanel=new ScorePanel();
        this.food=new Food();
        this.init();
    }

    init(){
        // 更改this 指向
        document.addEventListener('keydown',this.keydownHandler.bind(this));
        this.move();
    }

    keydownHandler(event:KeyboardEvent){
        this.direction=event.key?event.key:'';
    }

    move(){
        let X=this.snake.X;
        let Y=this.snake.Y;
        switch (this.direction){
            case 'ArrowUp':Y-=10;break;
            case 'ArrowDown':Y+=10;break;
            case 'ArrowLeft':X-=10;break;
            case 'ArrowRight':X+=10;break;
            default:break;
        }
        this.checkEat(X,Y);
        try {
            this.snake.X=X;
            this.snake.Y=Y;
        }catch (e:any){
            alert(e.message+'GAME OVER!');
            this.isAlive=false;
        }

        console.log('move---')
        if(this.isAlive){
            setTimeout(this.move.bind(this),300-(this.scorepanel.level-1)*30);
        }
    }

    checkEat(X:number,Y:number){
        if(X===this.food.X && Y===this.food.Y){
            console.log('蛇吃到食物了!');
            this.food.change();
            this.snake.grow();
            this.scorepanel.addScore();
        }
    }

}

export default GameControl;